#include "socked.hpp"
#include <poll.h>
#include <vector>

using namespace std;

#define MAX_NUM_FD 64
#define DEFAULT_DATA -1
class PollServer
{
public:
    PollServer()
        : socket_(8888)
    {
        for (auto &e : arr)
        {
            e.fd = DEFAULT_DATA;
            e.events = 0;
            e.revents = 0;
        }
    }

    ~PollServer()
    {
    }

    void init()
    {
        socket_.Socket();
        socket_.Bind();
        socket_.Listen();
    }

    void deal_fd()
    {
        // 遍历寻找
        for (auto &e : arr)
        {
            if (e.revents & POLLIN)
            {
                if (e.fd == socket_.sockfd_)
                {
                    // 处理连接请求
                    socket_.Accept();
                    for (auto &f : arr)
                    {
                        // 添加描述符
                        if (f.fd == DEFAULT_DATA)
                        {
                            log(Debug, "new link");
                            f.fd = socket_.lis_sockfd_;
                            f.events = POLLIN;
                            break;
                        }
                    }
                }
                else
                {
                    // 接收数据
                    char buf[1024];
                    int n = read(e.fd, buf, sizeof(buf));
                    if (n > 0)
                    {
                        buf[n] = 0;
                        cout << buf << endl;
                    }
                    else if (n == 0)
                    {
                        log(Warning, "stop connect");
                        close(e.fd);
                        e.events = 0;
                    }
                    else
                    {
                        log(Fatal, "read fail");
                        close(e.fd);
                        e.events = 0;
                    }
                }
            }
        }
    }

    void start()
    {
        arr[0].fd = socket_.sockfd_;
        arr[0].events = POLLIN;

        while (1)
        {
            int n = poll((pollfd *)arr, MAX_NUM_FD, 3000); // 等待3000ms
            if (n > 0)
            {
                deal_fd();
            }
            else if (n == 0)
            {
                log(Debug, "wait");
            }
            else
            {
                log(Warning, "poll fail");
            }
        }
    }

    Sock socket_;
    struct pollfd arr[MAX_NUM_FD];
};